package searcher;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;

import util.Configuration;

public class LuceneSearcher {

	public static void search(Directory directory, String term)
			throws CorruptIndexException, IOException {
		IndexSearcher searcher = new IndexSearcher(directory);
		Query query = new TermQuery(new Term("title", term));

		TopDocs rs = searcher.search(query, null, 10);
		System.out.println(rs.totalHits);

		if (rs.totalHits > 0) {
			Document firstHit = searcher.doc(rs.scoreDocs[0].doc);

			System.out.println(firstHit.getFieldable("title").name());
			System.out.println(firstHit.getFieldable("param").name());
			System.out.println(firstHit.getFieldable("review").name());
		}
	}

	public static void main(String[] args) {
		Directory indexDir = null;
		String term = "三防 智能 防水 手机 诺基亚";

		try {
			indexDir = SimpleFSDirectory.open(new File(
					Configuration.LUCENE_INDEX));

			@SuppressWarnings("deprecation")
			IndexSearcher searcher = new IndexSearcher(indexDir);
			System.out.println(searcher.getIndexReader().numDocs());

			TopDocs tfd = searcher.search(LuceneQueryParser.parse(term), 10);
			ScoreDoc[] hits = tfd.scoreDocs;

			System.out.println(hits.length);
			for (int i = 0; i < hits.length; ++i) {
				Document doc = searcher.doc(hits[i].doc);
				System.out.println(doc.getFieldable("title") + " "
						+ hits[i].toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
